// pages/llpurchase/llpurchase.js
var Ajax = require('../../utils/Ajax.js')
var utils = require('../../utils/util.js');
var config = require('../../base.conf.js').config;
var timer = null;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodstag: [],
    pageSize: 15,
    currentPage: 1,
    statusType: 'none',
    isauth:true,
    statuserro: false,
    scopewerun:false,
    autoplay:false,
    isinvitation: false, //是否显示兑换按钮
    getUserStep: '',
    moreType: 'none',
    banneList: [],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    utils.showLoading();
    this.refresh();
    this.setData({
      isauth: options.isauth==1 ? true:false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      userInfo: utils.getUserInfo(),
      getUserStep: utils.getUserStep()
    }, () => {
      this.lookgetSetting();
    })
  },
  refresh() { //下拉刷新
    var {
      moreType,
      currentPage,
      getUserStep
    } = this.data;
    if (moreType != "loading") {
      this.setData({
        currentPage: 1,
        moreType: 'none'
      }, () => {
        if (getUserStep && getUserStep.uuid) {
          this.updateSysStep(); //跟新步数
        }
        this.PlAdvertisLike();
        this.purchase();
      })
    }
  },
  PlAdvertisLike() {
    var that = this
    Ajax.post("PlAdvertisLike", {
      area: "1",//平台
      position: "11",//积分换轮播
    }).then((d) => {
      utils.hideLoading()
      var imglist = d.data
      if (d.status == 200) {
        that.setData({
          banneList: d.data
        })
      } else {
        utils.showtoast(d.msg)
      }
    }).catch((e) => {
      console.log(e)
      utils.hideLoading()
      utils.showtoast('网络错误,数据加载失败')
    })
  },
  onTappages(e) { //me跳转页面
    var {
      path
    } = e.currentTarget.dataset;
    utils.toPage(`/pages/${path}/${path}`)
  },
  Tapquantum() { //点击步数兑换
    var {
      getUserStep,
      scopewerun
    } = this.data;
    if (!scopewerun && getUserStep && getUserStep.sysStep == 0) { //没有授权步数并且初始化步数
      this.updateSysStep(true);
      return;
    }
    if (!getUserStep.sysStep) { //没有步数信息或者步数为0
      this.setData({
        isinvitation: true
      }, () => {
        this.showModal('isExchange');
      })
    } else {
      if (getUserStep && getUserStep.sysStep < 0) {
        return utils.showtoast('数据错误')
      }
      this.setData({
        preview: utils.multiply(getUserStep.convertRate || 0, getUserStep.sysStep || 0)
      }, () => {
        this.setData({
          isinvitation: false
        }, () => {
          this.showModal('isExchange');
        })
      })
    }
  },
  lookgetSetting() { //查看步数授权状态
    var { isauth } = this.data;
    isauth && wx.getSetting({
      success: (res) => {
        this.setData({
          scopewerun: res.authSetting['scope.werun'] || false,
          autoplay:true,
          getUserStep: utils.getUserStep() || null,
        }, () => {
          var { getUserStep}=this.data;
          if (getUserStep) {
            this.updateSysStep();
          }
        })
      }
    })
  },
  judgeWeRun() { //判断用户是否初始化步数
    var {
      getUserStep,
      scopewerun
    } = this.data;
    getUserStep = getUserStep || {}
    if (!getUserStep.uuid && app.getValueSync('unionId') && scopewerun) { //特殊情况判断是否有uuid
      app.getWeRun((status, msg) => {
        if (status) {
          this.setData({
            getUserStep: msg.data
          }, () => {
            this.updateSysStep(); //跟新步数
          })
        }
      }, false)
    } else if (getUserStep.uuid) {
      this.updateSysStep();
    }
  },
  updateSysStep(flag=false) { //更新系统步数
    var { getUserStep, scopewerun, isauth} = this.data;
    if (getUserStep && !scopewerun) {//如果授权过
      if (flag == false) {
        app.updataStep((status, msg) => { //没有步数更新信息
          this.setData({
            getUserStep: msg.data
          })
          utils.hideLoading();
          wx.stopPullDownRefresh();
        }, null, true)
      } else {
        app.getWeRun((status, msg) => {
          if (status) {
            this.setData({
              scopewerun: true,
              isauth: true,
              getUserStep: msg.data
            },()=>{
              this.parantset();
            })
            wx.stopPullDownRefresh();
          }
        }, true, false)
      }
      return;
    } else if (getUserStep && scopewerun && isauth){
      app.getWeRun((status, msg) => {
        if (status) {
          this.setData({
            scopewerun: true,
            getUserStep: msg.data,
          })
          wx.stopPullDownRefresh();
        } else {
          if (msg && msg.ststus == '该用户不存在或未授权') {
            utils.showLoading();
            wx.removeStorageSync('sysStep')
            this.setData({
              getUserStep: ''
            }, () => {
              wx.stopPullDownRefresh();
              setTimeout(() => {
                this.judgeWeRun();
              }, 500)
            })
          } else {
            if (msg && msg.data == '微信运动未授权') {
              this.setData({
                scopewerun: false,
                isauth: false
              })
            } else {
              this.parantset();
              this.setData({
                scopewerun: false,
                isauth: true
              })
            }
          }
        }
      }, true);
    }else{
      return utils.showtoast('数据错误')
    }
  },
  parantset(){
    var pages = getCurrentPages();
    if (pages.length >= 2 && pages[pages.length - 2].route == "pages/index/index") {
      pages[pages.length - 2].setData({
        isauth: true,
      })
    }
  },
  cancel(){
    this.closeModal('Model')
  },
  onClose() { //关闭兑换提示
    this.closeModal('isExchange');
  },
  toConfirmchang() {
    this.closeModal("isExchange");
    utils.showLoading();
    setTimeout(() => {
      this.showModal('Model')
      utils.hideLoading();
    }, 500)
  },
  onConfirmchang() { //确认兑换积分
    var {
      getUserStep
    } = this.data;
    if (getUserStep && getUserStep.sysStep > 0) {
      utils.showLoading();
      Ajax.post("exchangeBee", {
        uuid: getUserStep.uuid
      }).then((d) => {
        this.closeModal('Model')
        utils.hideLoading();
        if (d.status == 200&&d.code==0) {
          this.setData({
            ['getUserStep.integral']: d.data.total,
            ['getUserStep.sysStep']: 0
          }, () => {
            utils.showtoast('兑换成功')
            app.save("sysStep", JSON.stringify(this.data.getUserStep));
          })
        } else {
          utils.showtoast(d.data || d.msg || d.message || '服务器错误,请稍后重试')
        }
      }).catch((e) => {
        utils.hideLoading();
        utils.showtoast('兑换失败，请检查您的网络')
        this.closeModal('Model')
      })
    } else {
      this.closeModal('Model');
      utils.showtoast('没有可兑换的步数,去邀请好友赠送步数吧')
    }
  },
  //没有UID弹窗
  showModal(id) {
    var modal = this.selectComponent("#" + (id || 'noUid'));
    modal.show();
  },
  closeModal(e) { //关闭弹窗
    var id = this.onSetid(e);
    var modal = this.selectComponent("#" + (id || 'noUid'));
    modal.hide();
  },
  onSetid(e) { //弹出窗的ID获取
    var id = 'modal'
    if (typeof(e) == 'string') {
      id = e
    } else {
      id = e && (e.currentTarget.id || e.currentTarget.dataset.id);
    }
    return id;
  },
  gotoGoods(e) {
    var {
      productId,
      integral
    } = e.detail;
    utils.toPage(`/pages/goodsmain/goodsmain?productId=${productId}&onlineType=4&ischang=${integral ? 1:0}`)
  },
  purchase() { //查询商品列表
    var {
      pageSize,
      currentPage,
      options,
      moreType,
      changatv,
      userInfo
    } = this.data;
    Ajax.get("goodslist", {
      pageSize,
      currentPage,
      type:4
      // uid: userInfo&&userInfo.id || ''
    }).then((d) => {
      utils.hideLoading();
      wx.stopPullDownRefresh();
      if (d.status == 200) {
        moreType = "showText";
        var list = d.data && d.data.list || [];
        list.map((item) => {
          var strattime = new Date().getTime(); //现在的时间
          var endtimes = item.iffDate + strattime;
          if (!item.iffday && item.iffDate) {
            item.timesArr = this.dateDif(item.iffDate) || [null, null, null, null, 0];
            item.iffDate = Number(item.iffDate) - 1000 > 0 ? Number(item.iffDate) - 1000:0;
            item.state = (Number(item.iffDate) - 1000 > 0 ? 1 : 0)
          } else {
            item.iffDate = item.iffDate||0;
            item.state = item.iffDate  ? 1:0;
          }
        })
        list.length < pageSize ? moreType = "noMore" : moreType
        if (currentPage != 1) {
          list = this.data.goodstag.concat(list);
        }
        this.setData({
          goodstag: list,
          statusType: list.length > 0 ? 'none' : 'empty',
          statuserro: false,
          moreType
        }, () => {
          this.onEndtime()
        })
      } else {
        var {
          goodstag
        } = this.data;
        this.setData({
          moreType: "none",
          statusType: goodstag.length > 0 ? 'none' : 'empty',
          statuserro: goodstag.length > 0 ? false : true,
        })
        utils.showtoast(d.msg || d.data || '服务器错误,请稍后重试')
      }
    }).catch((e) => {
      console.log(e)
      utils.hideLoading();
      wx.stopPullDownRefresh();
      var {
        goodstag
      } = this.data;
      this.setData({
        moreType: "none",
        statusType: goodstag.length > 0 ? 'none' : 'empty',
        statuserro: goodstag.length > 0 ? false : true,
      })
      utils.showtoast('网络错误，请检查您的网络')
    })
  },
  onEndtime() {
    clearInterval(timer);
    timer = null;
    var {
      goodstag
    } = this.data;
    if (goodstag.length > 0) {
      timer = setInterval(() => {
        goodstag.map((item, index) => {
          var temp = 'goodstag' + '[' + index + '].timesArr'
          var state = 'goodstag' + '[' + index + '].state'
          var endtimes = 'goodstag' + '[' + index + '].iffDate'
          if (!item.iffday && item.iffDate) {
            var timesArr = (item.iffDate && this.dateDif(item.iffDate)) || [null, null, null, null];
            this.setData({
              [temp]: timesArr,
              [endtimes]: Number(item.iffDate) - 1000 > 0 ? Number(item.iffDate) - 1000:0,
              [state]: (Number(item.iffDate) - 1000 > 0 ? 1 : 0)
            })
          } else {
            this.setData({
              [endtimes]: item.iffDate ? item.iffDate : 0,
              [state]:item.iffDate ? 1 : 0
            })
          }
        })
      }, 1000);
    }
  },
  dateDif(date) { //处理倒计时
    if (date <= 0) {
      return null;
    }
    var days = date / 1000 / 60 / 60 / 24;
    var daysRound = Math.floor(days); //对一个数进行下舍入。
    var hours = date / 1000 / 60 / 60 - (24 * daysRound);
    var hoursRound = Math.floor(hours);
    var minutes = date / 1000 / 60 - (24 * 60 * daysRound) - (60 * hoursRound);
    var minutesRound = Math.floor(minutes);
    var seconds = date / 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
    var secondsRound = Math.floor(seconds);
    return [this.addZero(daysRound), this.addZero(hoursRound), this.addZero(minutesRound), this.addZero(secondsRound)];
  },
  addZero(numbers) { //小于10前面加一个零
    if (numbers < 10) {
      return "0" + numbers
    }
    return numbers;
  },
  onReachBottom: function() { //滚动触底加载
    var {
      moreType,
      currentPage,
    } = this.data;
    if (moreType == "showText") {
      var currentPage = currentPage + 1;
      this.setData({
        currentPage,
        moreType: "loading"
      }, () => {
        this.purchase();
      });
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.setData({
      autoplay: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    utils.showLoading();
    this.refresh();
  },
  onShareAppMessage(){
    this.closeModal('isExchange');
    var getUserStep = utils.getUserStep() || null;
    var weChatInfo = utils.getWechatInfo() || null;
    if (weChatInfo && getUserStep) {
      return {
        title: `${weChatInfo && weChatInfo.userInfo.nickName || '他'}发起了捐赠步数换礼物，快来帮TA！`,
        path: `/pages/sponsorship/sponsorship?uuid=${getUserStep.uuid}&shareId=${getUserStep.shareId || ''}`,
        imageUrl: '../../assets/img/step.png',
      }
    }
  }
})